﻿using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace MyAMS.Utility
{
    /// <summary>
    /// 容器扩展类
    /// </summary>
    public static class IUnityContainerExtensions
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        public static readonly string unityConfigurationFilePath = "~/{0}.config";

        private static readonly string unitySectionName = "unity";

        /// <summary>
        /// 配置容器
        /// </summary>
        /// <param name="parentContainer">父容器</param>
        /// <param name="configPath">配置文件路径</param>
        /// <returns>配置后的子容器</returns>
        public static IUnityContainer Configure(this IUnityContainer parentContainer, string configPath)
        {
            //IUnityContainer childContainer = parentContainer.CreateChildContainer();

            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configPath;
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None).GetSection(unitySectionName);
            section.Containers.Default.Configure(parentContainer);

            parentContainer.RegisterInstance(parentContainer);

            return parentContainer;
        }
    }
}
